package br.com.criativasystem.server;

import br.com.criativasystem.helper.BD;
import br.com.criativasystem.modelo.Login;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author
 * Lucas
 * Calixto
 */
public class ThreadServer extends Thread implements Serializable {

    private Socket socket;
    private Login login;
    private Boolean retorno = false;

    public ThreadServer(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            ObjectInputStream entrada = new ObjectInputStream(socket.getInputStream());
            login = (Login) entrada.readObject();

            ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
            saida.flush();
            saida.writeObject(selecionaLogin());

            entrada.close();
            saida.close();
        } catch (IOException ex) {
            System.out.println("Erro ao escrever ou ler o arquivo");
        } catch (ClassNotFoundException ex) {
            System.out.println("Classes não encontrada");
        }
    }

    private Boolean selecionaLogin() {
        String sql = "SELECT * FROM login WHERE usuarioLogin = ? AND senhaLogin = ?;";
        Connection conn = null;
        PreparedStatement stm = null;
        try {
            conn = new BD().getConexao();
            stm = conn.prepareStatement(sql);
            stm.setString(1, login.getUsuario());
            stm.setString(2, login.getSenha());
            ResultSet rs = stm.executeQuery();
            int qtRegistros = 0;
            for (qtRegistros = 0; rs.next(); qtRegistros++) {
            }
            if (qtRegistros == 1) {
                retorno = true;
            }
        } catch (SQLException ex) {
            System.out.println("Erro ao execultar consulta SQL");
        } finally {
            try {
                conn.close();
                stm.close();
            } catch (SQLException ex) {
                Logger.getLogger(ThreadServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return retorno;
    }
}
